package net.ba.map
{
	import com.google.maps.Copyright;
	import com.google.maps.CopyrightCollection;
	import com.google.maps.LatLng;
	import com.google.maps.LatLngBounds;
	import com.google.maps.TileLayerBase;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.geom.Point;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.utils.ByteArray;
	
	import mx.core.Application;
	import mx.utils.Base64Encoder;
	
	import net.ba.models.Cell;
	import net.ba.models.CellArray;
	import net.ba.utils.CellIdUtils;

	/**
	 * The ActiveServerLayer takes care of displaying the actual data on the map
	 * using server side polygon drawing. It extends TileLayerBase as it is an actual
	 * Tile fixed with google physical overlay. In the future this should be a
	 * a TileOverlay in order to support change of the base map, but the Google API
	 * still do not support this.
	 */
	public class ActiveServerLayer extends TileLayerBase
	{
		private var tileSize:Number;
		public var cellArray:CellArray = new CellArray();
		
		public function ActiveServerLayer(tileSize:Number)
		{
			
			
			var copyrightCollection:CopyrightCollection = new CopyrightCollection();
    		super(copyrightCollection, 14, 20);
			this.tileSize = tileSize;
			copyrightCollection.addCopyright(
        	new Copyright("CustomCopyright",
                      new LatLngBounds(new LatLng(-180, 90),
                                       new LatLng(180, -90)),
                      0,
                      "CustomTileProvider"));
		}
	  /**
	   * Creates and loads a tile (x, y) at the given zoom level.
	   * @param tilePos  Tile coordinates.
	   * @param zoom  Tile zoom.
	   * @return  Display object representing the tile.
	   */
	  public override function loadTile(tilePos:Point, zoom:Number):DisplayObject {
	    
	    var testLoader:Loader = new Loader();
	    var z:Number = 17 - zoom;
	    //var urlRequest:URLRequest = new URLRequest("http://localhost:8888/map/drawCell.php");
	    var urlRequest:URLRequest = new URLRequest("http://www.imastedev.com/ba/maps/drawCell.php");
	    var variables:URLVariables = new URLVariables();
	    variables.x = tilePos.x;
	    variables.y = tilePos.y;
	    variables.z = zoom;
	    variables.data = getSerializeData(tilePos,zoom);
	    urlRequest.data = variables;
	    urlRequest.method = URLRequestMethod.GET;
	    testLoader.load(urlRequest); 
	    testLoader.alpha =0.7;       
	    
	    return testLoader;
	  }
	  
	  private function getSerializeData(tile:Point= null, zoom:Number=NaN):String {
	  	var s:String='';
	  	
	  	//Calculate the bounding box in cellIds to avoid sending too much data to the server
  		var zoomLevel:Number = 17 - zoom;
      	//LowerLeft Corner
		var tileIndexLL:Point = new Point(256*tile.x, 256*(tile.y+1));
		//UpperRight Corner
		var tileIndexUR:Point = new Point(256*(tile.x+1), 256*(tile.y));		
		var LL:LatLng = new LatLng(CellIdUtils.YToL(zoomLevel,tileIndexLL.y),CellIdUtils.XToL(zoomLevel,tileIndexLL.x));
		var UR:LatLng = new LatLng(CellIdUtils.YToL(zoomLevel,tileIndexUR.y),CellIdUtils.XToL(zoomLevel,tileIndexUR.x));
		var cellLL:int = CellIdUtils.toCellId(LL.lat(),LL.lng());
		var cellUR:int = CellIdUtils.toCellId(UR.lat(),UR.lng());	
		if (cellLL>360)
			cellLL-=360;
		if (cellUR<64440)
			cellUR+=360;
			
			
	  	for (var c:* in cellArray.cells) {
	  		if (tile!=null) {
	  			if (CellIdUtils.isCellIdInBoundingBox(c,cellLL,cellUR)) {
		  			s=s+c+"b"+cellArray.getCellCount(c) + "a";
	  			}
	  		} else {
		  		s=s+c+"b"+cellArray.getCellCount(c) + "a";
	  		}
	  	}
	  	//remove the last |
	  	s = s.substr(0, s.length-1);
	  	return s;
	  }
	  

	  public function addCell(cell:Cell,forceRedraw:Boolean = true):void {
	  	var found:Boolean=false;
	  	cellArray.sumCell(cell.cellId,cell.count);
		
		if (forceRedraw) {
			redraw();
		}
  	
	  }
	  
		public function addCellByLatLng(latLng:LatLng,count:Number=1,forceRedraw:Boolean = false):void {	
			addCell(new Cell(CellIdUtils.toCellId(latLng.lat(),latLng.lng()),count),forceRedraw);
		}	  
	  
	  public function redraw():void {
	  	Application.application.mapContainer.redrawActiveServerLayer();
	  }
	  
	}
}